package com.jinbai.repo;

import com.jinbai.data_object.UserDO;
import com.jinbai.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class UserRepo {
    @SneakyThrows   // lombok，可以让我们不添加 throws 也可以正常抛出受查异常
    public void registerUser(UserDO userDO) {
        // 这里进行 SQL 操作
        String sql = "insert into users (username, password) values (?, ?)";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, userDO.getUsername());
                ps.setString(2, userDO.getPassword());

//                Log.println("执行 SQL: " + ps.toString());
                ps.executeUpdate();

                // 得到自增 id 作为 uid
                try (ResultSet rs = ps.getGeneratedKeys()) {
                    rs.next();
                    userDO.setUid(rs.getInt(1));
                }
            }
        }
    }

    @SneakyThrows
    public UserDO selectUserByUsername(String username) {
        UserDO userDO = new UserDO(username);
        try (Connection con = DBUtil.connection()) {
            String sql = "select uid, password from users where username = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setString(1, username);
                try (final ResultSet rs = ps.executeQuery()) {
                    if (!rs.next()) {
                        return null;
                    }
                    userDO.setUid(rs.getInt("uid"));
                    userDO.setPassword(rs.getString("password"));
                    return userDO;
                }
            }
        }
    }
}
